package webone.registered.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import webone.javabean.Users;
import webone.usersDAO.UserDAOMapper;

/**
 * Servlet implementation class RegistedServlet
 */
@WebServlet("/registedServlet")
public class RegistedServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Map<String,String> userInfo=new HashMap<>();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegistedServlet() {
        super();
    	}
    public SqlSessionFactory getSqlSessionFactory() throws IOException {
			String resource = "mybatis-config.xml";
			InputStream inputStream = Resources.getResourceAsStream(resource);
			return new SqlSessionFactoryBuilder().build(inputStream);
		}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		SqlSessionFactory sqlSessionF=getSqlSessionFactory();
		SqlSession session=sqlSessionF.openSession();
		UserDAOMapper userMapper=session.getMapper(UserDAOMapper.class);
		request.setCharacterEncoding("utf-8");
		Enumeration<String> parameters=request.getParameterNames();		
		while(parameters.hasMoreElements()) {
			String key = parameters.nextElement();
			String value=request.getParameter(key);
			userInfo.put(key, value);			
		}
		int age=Integer.parseInt(userInfo.get("age"));
		Users user=new Users(userInfo.get("userNike"),userInfo.get("lastName"),userInfo.get("password"),age,userInfo.get("email"));
		userMapper.addOneUser(user);
		session.commit();
	}

}
